package com.yiquan.video.service;

import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import com.alibaba.fastjson.JSON;
import com.aliyun.oss.OSS;
import com.google.common.collect.ImmutableMap;
import com.yiquan.video.client.UserClient;
import com.yiquan.video.config.OssPropertiesConfig;
import com.yiquan.video.dao.VideoBehaveDao;
import com.yiquan.video.pojo.UserActivity;
import com.yiquan.video.pojo.VideoBehave;
import com.yiquan.video.pojo.VideoDTO;
import entity.PageResult;
import entity.Result;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;

import org.springframework.web.multipart.MultipartFile;
import util.IdWorker;

import com.yiquan.video.dao.VideoDao;
import com.yiquan.video.pojo.Video;
import util.ObjectUtils;

/**
 * 服务层
 *
 * @author Administrator
 */
@Service
@Slf4j
public class VideoService {

    @Autowired
    private VideoDao videoDao;

    @Autowired
    private IdWorker idWorker;

    @Autowired
    private UserClient userClient;

    @Autowired
    private OssPropertiesConfig ossPropertiesConfig;

    @Autowired
    private VideoBehaveDao videoBehaveDao;

    @Autowired
    private RedisTemplate redisTemplate;

    private static final String APP_NAME = "yi_quan/video";
    private static final String VIDEO_THUMBNAIL_URL_SUFFIX = "?x-oss-process=video/snapshot,t_0,f_jpg,w_0,h_0,m_fast,ar_auto";

    private static final Integer VIDEO_STATE_NORMAL = 0;
    private static final Integer VIDEO_BEHAVE_NORMAL = 0;

    private static final Integer OPERATE_CREATE = 0; //评论
    private static final Integer OPERATE_THUMB = 1;   //点赞
    private static final Integer OPERATE_COMMENT = 2;   //评论
    private static final Integer OPERATE_COLLECT = 3;  //收藏
    private static final Integer OPERATE_FORWARD = 4;   //转发

    public static final String FOLLOW_VIDEO_SUFFIX = "FOLLOW_VIDEO_SUFFIX_";
    public static final String FRIEND_VIDEO_SUFFIX = "FRIEND_VIDEO_SUFFIX_";
    private static final String[] FILE_TYPE = new String[]{".bmp", ".jpg", ".jpeg",
            ".gif", ".png", ".avi", ".mp3", ".mov"};


    @Qualifier("taskExecutor")
    @Autowired
    private ThreadPoolTaskExecutor taskExecutor;


    private static final String ViDEO_MODULE_ID = "VIDEO_MODULE_ID";

    /**
     * 获取用户id (20000000-29999999)
     *
     * @return
     */
    public Long getUniqueId() {
        redisTemplate.opsForValue().setIfAbsent(ViDEO_MODULE_ID, 20000000L);
        Long temporaryUserId = redisTemplate.opsForValue().increment(ViDEO_MODULE_ID);
        return temporaryUserId;
    }

    /**
     * 查询全部列表
     *
     * @return
     */
    public List<Video> findAll() {
        return videoDao.findAll();
    }


    /**
     * 条件查询+分页
     * 视频推荐逻辑：
     * 关注模块：
     * 根据创建时间逆序排序
     *
     * @param whereMap      条件map
     * @param page          分页
     * @param size          大小
     * @param operateUserId 操作用户id
     * @return
     */
    public Page<Video> findSearch(Map whereMap, int page, int size, Long operateUserId) {
        if (whereMap == null) {
            whereMap = new HashMap();
        }
        whereMap.put("status", 0);
        Specification<Video> specification = createSpecification(whereMap);
        PageRequest pageRequest = PageRequest.of(page - 1, size, Sort.by(Sort.Direction.DESC, "createDate"));//按照时间降序排列
        Page<Video> videoPage = videoDao.findAll(specification, pageRequest);
        videoPage.getContent().stream().forEach(video -> {
            LinkedHashMap user = (LinkedHashMap) userClient.findByUserId(video.getVideo_uid()).getData();
            if (user != null) {
                video.setUser_nickName((String) user.get("nick_name"));
                video.setUser_avatar((String) user.get("avatar"));
                video.setVideo_thumbnail(video.getVideo_url() + VIDEO_THUMBNAIL_URL_SUFFIX);
            }
            if (operateUserId != null) {
                if (videoBehaveDao.findOneByVideoIdAndUserIdAndOperate(video.getVideo_id(), operateUserId, OPERATE_THUMB) != null) {
                    video.setIsLike(true);
                } else {
                    video.setIsLike(false);
                }
            } else {
                video.setIsLike(false);
            }
        });
        return videoPage;
    }


    /**
     * 条件查询
     *
     * @param whereMap
     * @return
     */
    public List<Video> findSearch(Map whereMap) {
        Specification<Video> specification = createSpecification(whereMap);
        return videoDao.findAll(specification);
    }

    /**
     * 根据ID查询实体
     *
     * @param id
     * @return
     */
    public Video findById(Long id) {

        return videoDao.findById(id).get();
    }

    public Video findByVideoId(Long videoId) {
        Video video = videoDao.findByVideoId(videoId);
        video.setVideo_thumbnail(video.getVideo_url() + VIDEO_THUMBNAIL_URL_SUFFIX);
        Result byUserId = userClient.findByUserId(video.getVideo_uid());
        Map data = (Map) byUserId.getData();
//        Map data = (Map) userClient.findByUserId(video.getVideo_uid()).getData();
        video.setUser_nickName((String) data.get("nick_name"));
        video.setUser_avatar((String) data.get("avatar"));
        video.setUser_type((String) data.get("user_type"));
        return video;
    }

    /**
     * 增加
     *
     * @param video
     */
    public void add(Video video) {
        video.setVideo_id(getUniqueId());
        video.setCreateDate(new Date());
        video.setCollects(0);
        video.setComments(0);
        video.setThumbs(0);
        video.setForwards(0);
        video.setVideo_status(VIDEO_STATE_NORMAL);
        videoDao.save(video);
    }

    /**
     * 修改
     *
     * @param video
     */
    public void update(Video video, Long id) {
        video.setId(id);
        video.setVideo_id(getUniqueId());
        video.setCreateDate(new Date());
        videoDao.save(video);
    }


    /**
     * 删除
     *
     * @param userId
     * @param videoId
     */
    public void deleteById(Long userId, Long videoId) {
        Video video = new Video();
        video.setVideo_status(3);
        updateByVideoId(video, videoId);
        userClient.updateUserWorkNums(userId, -1);
    }

    /**
     * Video动态条件构建
     *
     * @param searchMap
     * @return
     */
    private Specification<Video> createSpecification(Map searchMap) {

        return new Specification<Video>() {

            @Override
            public Predicate toPredicate(Root<Video> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                List<Predicate> predicateList = new ArrayList<Predicate>();
                // 视频url
                if (searchMap.get("status") != null) {
                    predicateList.add(cb.equal(root.get("video_status").as(Integer.class), searchMap.get("status")));
                }
                if (searchMap.get("content") != null && !"".equals(searchMap.get("content"))) {
                    predicateList.add(cb.like(root.get("video_description").as(String.class), "%" + (String) searchMap.get("content") + "%"));
                }
                if (searchMap.get("userId") != null) {
                    predicateList.add(cb.equal(root.get("video_uid").as(Long.class), searchMap.get("userId")));
                }
                if (searchMap.get("videoId") != null) {
                    predicateList.add(cb.equal(root.get("video_id").as(Long.class), searchMap.get("videoId")));
                }
                if (searchMap.get("videoThumbNail") != null) {
                    predicateList.add(cb.equal(root.get("video_thumbnail").as(String.class), searchMap.get("videoThumbNail")));
                }
                if (searchMap.get("userType") != null) {
                    predicateList.add(cb.equal(root.get("user_type").as(String.class), searchMap.get("userType")));
                }
                if (StringUtils.isNotBlank((String) searchMap.get("startCreateDate")) && StringUtils.isNotBlank((String) searchMap.get("endCreateDate"))) {
                    predicateList.add(cb.between(root.get("createDate").as(String.class), (String) searchMap.get("startCreateDate"), (String) searchMap.get("endCreateDate")));
                }


                return cb.and(predicateList.toArray(new Predicate[predicateList.size()]));
            }
        };
    }

    /**
     * VideoBahave动态条件构建
     *
     * @param searchMap
     * @return
     */
    private Specification<VideoBehave> createVideoBehaveSpecification(Map searchMap) {

        return new Specification<VideoBehave>() {

            @Override
            public Predicate toPredicate(Root<VideoBehave> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                List<Predicate> predicateList = new ArrayList<Predicate>();

                if (searchMap.get("user_id") != null) {
                    predicateList.add(cb.equal(root.get("user_id").as(Long.class), searchMap.get("user_id")));
                }

                if (searchMap.get("operate") != null) {
                    predicateList.add(cb.equal(root.get("operate").as(Integer.class), searchMap.get("operate")));
                }

                return cb.and(predicateList.toArray(new Predicate[predicateList.size()]));
            }
        };
    }

    public VideoDTO uploadVideo(MultipartFile multipartFile, Long userId) {
        // yourEndpoint填写Bucket所在地域对应的Endpoint。以华东1（杭州）为例，Endpoint填写为https://oss-cn-hangzhou.aliyuncs.com。
        for (String type :
                FILE_TYPE) {
            if (StringUtils.endsWithIgnoreCase(multipartFile.getOriginalFilename(), type)) {
                return null;
            }
        }
        String endpoint = ossPropertiesConfig.getEndpoint();
        // 创建OSSClient实例。
        OSS ossClient = null;
        try {
            ossClient = ossPropertiesConfig.ossClient();//获取客户端实例
            InputStream inputStream = multipartFile.getInputStream();//获取文件输入流
            String originalFilename = multipartFile.getOriginalFilename();//获取原文件名
            String suffix = null;//得到文件后缀名
            if (originalFilename != null) {
                suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
            }
            String bucketName = ossPropertiesConfig.getBucketName();//获取存储桶名
            String dateDir = new SimpleDateFormat("yyyy/MM/dd").format(new Date());//创建日期目录
            long videoId = getUniqueId();
            // TODO: 2021/12/27 需要考虑后缀的是否为图片或者是视频的判断
            String newFileName = videoId + suffix;//新文件名
            String fileUrl = APP_NAME + "/" + dateDir + "/" + newFileName;//阿里云的存储路径
            //      填写Byte数组。
            //		byte[] content = "Hello OSS".getBytes();
            // 依次填写Bucket名称（例如examplebucket）和Object完整路径（例如exampledir/exampleobject.txt）。Object完整路径中不能包含Bucket名称。
            ossClient.putObject(bucketName, fileUrl, inputStream);

            String videoUrl = "https://" + bucketName + "." + endpoint + "/" + fileUrl;
            //文件入库
            Video video = new Video();
            video.setVideo_url(videoUrl);
            video.setVideo_uid(userId);
            video.setVideo_id(videoId);
            video.setVideo_status(VIDEO_STATE_NORMAL);
            video.setVideo_thumbnail(videoUrl + VIDEO_THUMBNAIL_URL_SUFFIX);
            video.setCreateDate(new Date());
            video.setForwards(0);
            video.setThumbs(0);
            video.setComments(0);
            video.setCollects(0);
            videoDao.save(video);
            VideoDTO videoDTO = new VideoDTO();
            videoDTO.setVideo_id(videoId);
            videoDTO.setVideo_thumbnail(videoUrl + VIDEO_THUMBNAIL_URL_SUFFIX);
            userClient.updateUserWorkNums(userId, 1);
            return videoDTO;//返回视频缩略图
        } catch (IOException e) {
            log.error("用户：{} 上传视频失败");
            return null;
        } finally {
            // 关闭OSSClient。
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }

    /**
     * 点赞评论添加抽象
     *
     * @param videoId
     * @param userId
     * @param operate
     * @return
     */
    public boolean operateVideo(Long videoId, Long userId, Integer operate) {
        VideoBehave videoBehave = new VideoBehave();
        videoBehave.setOperate(operate);
        videoBehave.setVideo_id(videoId);
        videoBehave.setUser_id(userId);
        videoBehave.setStatus(VIDEO_BEHAVE_NORMAL);
        videoBehave.setOperateTime(new Date());
        videoBehaveDao.save(videoBehave);
        return true;
    }

    /**
     * 点赞评论等修改抽象
     *
     * @param videoId
     * @param modify
     * @param operate
     */
    public void modifyVideoOperate(Long videoId, Integer modify, Integer operate) {

        if (Objects.equals(operate, OPERATE_THUMB)) {
            videoDao.modifyThumbs(videoId, modify);
        } else if (Objects.equals(operate, OPERATE_COMMENT)) {
            videoDao.modifyComments(videoId, modify);
        } else if (Objects.equals(operate, OPERATE_COLLECT)) {
            videoDao.modifyCollects(videoId, modify);
        } else if (Objects.equals(operate, OPERATE_FORWARD)) {
            videoDao.modifyForwards(videoId, modify);
        }

    }

    public VideoBehave getOperateMsg(Long videoId, Long userId, Integer operate) {
        return videoBehaveDao.findOneByVideoIdAndUserIdAndOperate(videoId, userId, operate);
    }

    private boolean deleteByVideoIdAndUserIdAndOperate(Long videoId, Long userId, Integer operate) {
        videoBehaveDao.deleteByVideoIdAndUserIdAndOperate(videoId, userId, operate);
        return true;
    }

    public boolean thumpUpVideo(Long videoId, Long userId) {
        VideoBehave operateMsg = getOperateMsg(videoId, userId, OPERATE_THUMB);
        if (operateMsg == null) {
            operateVideo(videoId, userId, OPERATE_THUMB);
            modifyVideoOperate(videoId, 1, OPERATE_THUMB);
            new Thread(()->{
                Video byVideoId = findByVideoId(videoId);
                UserActivity userActivity = new UserActivity();
                userActivity.setActivity(6);
                userActivity.setFrom_user_id(userId);
                userActivity.setTo_user_id(byVideoId.getVideo_uid());
                userActivity.setBiz_no(videoId);
                userClient.addUserActivity(userActivity);
            }).run();
        } else {
            deleteByVideoIdAndUserIdAndOperate(videoId, userId, OPERATE_THUMB);
            modifyVideoOperate(videoId, -1, OPERATE_THUMB);
        }

        return true;
    }


    public boolean collectVideo(Long videoId, Long userId) {
        VideoBehave operateMsg = getOperateMsg(videoId, userId, OPERATE_COLLECT);
        if (operateMsg == null) {
            operateVideo(videoId, userId, OPERATE_COLLECT);
            modifyVideoOperate(videoId, 1, OPERATE_COLLECT);

        } else {
            deleteByVideoIdAndUserIdAndOperate(videoId, userId, OPERATE_COLLECT);
            modifyVideoOperate(videoId, -1, OPERATE_COLLECT);
        }
        return true;
    }

    public boolean forwardVideo(Long videoId, Long userId) {
        VideoBehave operateMsg = getOperateMsg(videoId, userId, OPERATE_FORWARD);
        if (operateMsg == null) {
            operateVideo(videoId, userId, OPERATE_FORWARD);
            modifyVideoOperate(videoId, 1, OPERATE_FORWARD);
        } else {
            deleteByVideoIdAndUserIdAndOperate(videoId, userId, OPERATE_FORWARD);
            modifyVideoOperate(videoId, -1, OPERATE_FORWARD);
        }
        return true;
    }


    public Map<String, Integer> countVideoOperate(Long videoId) {
        return videoDao.countVideoOperate(videoId);
    }

    public void modifyVideoCommentByVideoId(Long videoId, Integer modify) {
        modifyVideoOperate(videoId, modify, OPERATE_COMMENT);
    }


    public List<Video> getVideoByUserIdAndOperate(Long userId, Integer operate, Integer page, Integer size) {
        Map searchMap = new HashMap();
        searchMap.put("user_id", userId);
        searchMap.put("operate", operate);
        Specification<VideoBehave> specification = createVideoBehaveSpecification(searchMap);
        PageRequest pageRequest = PageRequest.of(page - 1, size, Sort.by(Sort.Direction.DESC, "operateTime"));//按照时间降序排列
        List<VideoBehave> content = videoBehaveDao.findAll(specification, pageRequest).getContent();
        System.out.println(content);
        List<Long> videoIdList = content.stream().map(VideoBehave::getVideo_id).collect(Collectors.toList());
        List<Video> videoList = new ArrayList<>();
        for (Long videoId : videoIdList) {
            Video video = videoDao.findByVideoId(videoId);
            videoList.add(video);

        }
        return videoList;
    }

    public Integer countVideoByUserIdAndOperate(Long userId, Integer operate) {
        return videoBehaveDao.countByVideoIdAndOperate(userId, operate);
    }

    public boolean updateByVideoId(Video video, Long videoId) {
        taskExecutor.execute(() -> {
            List<String> videoType = video.getType();
            Video byVideoId = videoDao.findByVideoId(videoId);
            ObjectUtils.copyPropertiesIgnoreNull(video, byVideoId);
            videoDao.save(byVideoId);

        });
        return true;
    }


    public Integer getUserVideoTotalThumbs(Long userId) {
        return videoDao.getUserVideoTotalThumbs(userId);
    }

    public Page<Video> findBySearch(Map map, int page, int size) {
        Specification<Video> specification = createSpecification(map);
        PageRequest pageRequest = PageRequest.of(page - 1, size);
        return videoDao.findAll(specification, pageRequest);
    }

    public void batchDelete(List<Long> videoIds) {
        videoIds.forEach(videoId -> {
            Video byVideoId = videoDao.findByVideoId(videoId);
            deleteById(byVideoId.getVideo_id(), videoId);
        });
    }

    public Page<Video> getTeacherVideo(int page, int size, Long operateUserId) {
        HashMap map = new HashMap();
        map.put("userType", "T");
        Page<Video> search = findSearch(map, page, size, operateUserId);
        if (operateUserId != null) {
            search.getContent().forEach(video -> {
                Result followTheUserByUserId = userClient.isFollowTheUserByUserId(operateUserId, video.getVideo_uid());
                video.setIsFollow((boolean) followTheUserByUserId.getData());
            });
        }
        return search;
    }

    /**
     * 获取关注板块视频
     * 若有userId（登录） 获取所有关注的用户的视频并且按照创建时间倒叙输出
     * 若没有则按照创建时间倒叙输出
     *
     * @param page
     * @param size
     * @param operateUserId
     * @return
     */
    public PageResult<Video> getFollowVideo(int page, int size, Long operateUserId) {
        if (operateUserId == null) {
            Page<Video> search = findSearch(null, page, size, operateUserId);
            return new PageResult<Video>(search.getTotalElements(), search.getContent());
        } else {
            List range = redisTemplate.opsForList().range(FOLLOW_VIDEO_SUFFIX + operateUserId, 0, -1);

            if (range == null || range.size() == 0) {
                Result userActivityAll = userClient.getUserActivityAll(operateUserId, 0);
                Object data = userActivityAll.getData();
                List<Long> userIds = JSON.parseArray(JSON.toJSONString(data), Long.class);
                List<Video> videoList = new ArrayList<>();
                for (Long userId : userIds) {
                    List<Video> videoByUserId = videoDao.findByUserId(userId);
                    videoList.addAll(videoByUserId);
                }
                if (videoList == null || videoList.size() == 0) {
                    return new PageResult<Video>(0L, videoList);
                }
                for (Video video : videoList) {
                    LinkedHashMap user = (LinkedHashMap) userClient.findByUserId(video.getVideo_uid()).getData();
                    if (user != null) {
                        video.setUser_nickName((String) user.get("nick_name"));
                        video.setUser_avatar((String) user.get("avatar"));
                        video.setVideo_thumbnail(video.getVideo_url() + VIDEO_THUMBNAIL_URL_SUFFIX);
                    }
                    if (operateUserId != null) {
                        if (videoBehaveDao.findOneByVideoIdAndUserIdAndOperate(video.getVideo_id(), operateUserId, OPERATE_THUMB) != null) {
                            video.setIsLike(true);
                        } else {
                            video.setIsLike(false);
                        }
                    } else {
                        video.setIsLike(false);
                    }
                    video.setIsFollow(true);
                }
                List<Video> collectVideo = videoList.stream().sorted(new Comparator<Video>() {
                    @Override
                    public int compare(Video o1, Video o2) {
                        return o1.getCreateDate().compareTo(o2.getCreateDate());
                    }
                }).collect(Collectors.toList());
                redisTemplate.opsForList().leftPushAll(FOLLOW_VIDEO_SUFFIX + operateUserId, collectVideo);
            }
            List list = redisTemplate.opsForList().range(FOLLOW_VIDEO_SUFFIX + operateUserId, (page - 1) * size, page * size - 1);
            Long redisSize = redisTemplate.opsForList().size(FOLLOW_VIDEO_SUFFIX + operateUserId);
            List<Video> videoList = new ArrayList<>();
            list.forEach(o1 -> {
                String s = JSON.toJSONString(o1);
                Video video = JSON.parseObject(s, Video.class);
                video.setIsFollow(true);
                videoList.add(video);
            });
            if (videoList.size() == 0) {
                Page<Video> search = findSearch(null, page, size, operateUserId);
                return new PageResult<Video>(search.getTotalElements(), search.getContent());
            }
            return new PageResult<Video>(redisSize, videoList);

        }
    }

    /**
     * 获取朋友板块视频
     *
     * @param
     * @return
     */
    public PageResult<Video> getFriendVideo(int page, int size, Long operateUserId) {
        List range = redisTemplate.opsForList().range(FRIEND_VIDEO_SUFFIX + operateUserId, 0, -1);
        if (range == null || range.size() == 0) {
            Result userActivityAll = userClient.getFriendListUserId(operateUserId, 0);
            Object data = userActivityAll.getData();
            List<Long> userIds = JSON.parseArray(JSON.toJSONString(data), Long.class);
            List<Video> videoList = new ArrayList<>();
            for (Long userId : userIds) {
                List<Video> videoByUserId = videoDao.findByUserId(userId);
                videoList.addAll(videoByUserId);
            }
            if (videoList == null || videoList.size() == 0) {
                return new PageResult<Video>(0L, videoList);
            }
            for (Video video : videoList) {
                LinkedHashMap user = (LinkedHashMap) userClient.findByUserId(video.getVideo_uid()).getData();
                if (user != null) {
                    video.setUser_nickName((String) user.get("nick_name"));
                    video.setUser_avatar((String) user.get("avatar"));
                    video.setVideo_thumbnail(video.getVideo_url() + VIDEO_THUMBNAIL_URL_SUFFIX);
                }
                if (operateUserId != null) {
                    if (videoBehaveDao.findOneByVideoIdAndUserIdAndOperate(video.getVideo_id(), operateUserId, OPERATE_THUMB) != null) {
                        video.setIsLike(true);
                    } else {
                        video.setIsLike(false);
                    }
                } else {
                    video.setIsLike(false);
                }
            }
            List<Video> collectVideo = videoList.stream().sorted(Comparator.comparing(Video::getCreateDate)).collect(Collectors.toList());
            redisTemplate.opsForList().leftPushAll(FRIEND_VIDEO_SUFFIX + operateUserId, collectVideo);
        }
        List list = redisTemplate.opsForList().range(FRIEND_VIDEO_SUFFIX + operateUserId, (page - 1) * size, page * size - 1);
        Long redisSize = redisTemplate.opsForList().size(FRIEND_VIDEO_SUFFIX + operateUserId);
        List<Video> videoList = new ArrayList<>();
        list.forEach(o1 -> {
            String s = JSON.toJSONString(o1);
            Video video = JSON.parseObject(s, Video.class);
            video.setIsFollow(true);
            videoList.add(video);
        });
        if (videoList.size() == 0) {
            Page<Video> search = findSearch(null, page, size, operateUserId);
            return new PageResult<Video>(search.getTotalElements(), search.getContent());
        }
        return new PageResult<Video>(redisSize, list);

    }


    public PageResult<Video> getRecommendVideo(int page, int size, Long operateUserId) {
        Map map = new HashMap();
        map.put("status", 0);
        Specification<Video> specification = createSpecification(map);
        List<Sort.Order> orders = new ArrayList<>();
        orders.add(new Sort.Order(Sort.Direction.DESC, "thumbs"));
        orders.add(new Sort.Order(Sort.Direction.DESC, "createDate"));
        Sort sort = Sort.by(orders);
        /**
         * 按照时间降序排列
         */
        PageRequest pageRequest = PageRequest.of(page - 1, size, sort);

        Page<Video> videoPage = videoDao.findAll(specification, pageRequest);

        if (operateUserId != null) {
            videoPage.getContent().forEach(video -> {
                Result followTheUserByUserId = userClient.isFollowTheUserByUserId(operateUserId, video.getVideo_uid());
                video.setIsFollow((boolean) followTheUserByUserId.getData());
                Map data = (Map) userClient.findByUserId(video.getVideo_uid()).getData();
                video.setUser_avatar((String) data.get("avatar"));
                video.setUser_nickName((String) data.get("nick_name"));
                if (videoBehaveDao.findOneByVideoIdAndUserIdAndOperate(video.getVideo_id(), operateUserId, OPERATE_THUMB) != null) {
                    video.setIsLike(true);
                } else {
                    video.setIsLike(false);
                }
            });
        }
        return new PageResult<>(videoPage.getTotalElements(), videoPage.getContent());
    }

    public Video getVideoByUserIdAndOperateUserId(Long userId,Long videoId) {
        Video video = findByVideoId(videoId);
        VideoBehave videoBehave = videoBehaveDao.findOneByVideoIdAndUserIdAndOperate(videoId, userId, OPERATE_THUMB);
        if (videoBehave!=null){
            video.setIsLike(true);
        }
        return video;
    }
}
